#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os,sys
PyPath=os.path.abspath(__file__)
BasePyPath = os.path.dirname(PyPath)
sys.path.insert(0,BasePyPath)
os.chdir(BasePyPath)

from flask import Flask, jsonify, request, redirect, render_template, Response, send_from_directory
from flask_cors import CORS
from image_infer import *
import datetime
import random


# 随机文件名
def create_random_name():  # 生成唯一的图片的名称字符串，防止图片显示时的重名问题
    nowTime = datetime.datetime.now().strftime("%Y%m%d%H%M%S")  # 生成当前时间
    randomNum = random.randint(0, 100)  # 生成的随机整数n，其中0<=n<=100
    if randomNum <= 10:
        randomNum = str(0) + str(randomNum)
    uniqueNum = str(nowTime) + str(randomNum)
    return uniqueNum


# 配置
port = 80
allowed_extension = ['png', 'jpg', 'jpeg', 'wmv', 'avi', 'dat', 'asf', 'mpeg', 'mpg', 'rm', 'rmvb', 'ram', 'flv', 'mp4', '3gp', 'mov', 'divx', 'dv', 'vob', 'mkv', 'qt', 'cpk', 'fli', 'flc', 'f4v', 'm4v', 'mod', 'm2t', 'swf', 'webm', 'mts', 'm2ts']


# Flask
app = Flask(__name__)
CORS(app, resources=r'/*')


# 接口文档页面
@app.route('/', methods=['GET', 'POST'])
@app.route('/index.html', methods=['GET', 'POST'])
def index():
    return render_template('index.html')

# 口罩识别接口
@app.route('/face/res', methods=['POST'])
def face_compare():
    print_split_line()
    # 获取、校验请求参数
    try:
        key = 'img'
        filename = request.files[key].filename
    except:
        try:
            key = 'video'
            filename = request.files[key].filename
        except:
            return build_api_result(1010, "请求参数错误", {})
        

    
    # 检查文件扩展名
    if not allowed_file(filename):
        return build_api_result(1020, "存在格式不正确的文件", {})
    
    #文件名随机化
    EndStr = filename.split('.')[-1]
    filename = str(create_random_name())+ '.' +EndStr
    
    if key == 'img':
        try:
            #保存图片
            img = request.files.get(key)
            img.save(BasePyPath +'/upload/'+filename)
            
            #识别
            path = BasePyPath +'/upload/'+filename
            predict_images(parse_args(path))

            #返回结果
            img_res = "/static/result/result."+filename
            return render_template('image.html',img_res=img_res)
        except:
            return build_api_result(1, "识别失败", {})
    elif key == 'video':
        try:
            #保存视频
            video = request.files.get(key)
            video.save(BasePyPath +'/upload/'+filename)
            
            #识别
            os.system('python3 '+ BasePyPath +'/video_infer.py --video_path '+ BasePyPath +'/upload/' + filename)

            #返回结果
            video_res = "/static/result/result."+filename
            if os.path.exists("."+video_res) is not True:
                return build_api_result(1, "识别失败", {})
            return render_template('video.html',video_res=video_res)
        except:
            return build_api_result(1, "识别失败", {})
        pass
    else:
        return build_api_result(1, "识别失败", {})

# 检查文件扩展名
def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in allowed_extension


# 构建接口返回结果
def build_api_result(code, message, data):
    result = {
        "code": code,
        "message": message,
        "data": data
    }
    print("Response data:", result)
    return jsonify(result)


# 打印分割线
def print_split_line():
    print("=" * 90)


if __name__ == "__main__":
    
    # Run
    app.config['JSON_AS_ASCII'] = False
    app.run(host='0.0.0.0', port=port, debug=False, use_reloader=False)
    print_split_line()